package org.codefinger.json.serializer;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.codefinger.json.util.magic.MagicAttribute;
import org.codefinger.json.util.magic.MagicPojo;

public class SerializerForPojo implements JSONSerializer {

	private PojoFieldSerializer[]	serializers;

	public SerializerForPojo(Class<?> pojoClass) {
		MagicPojo<?> magicPojo = MagicPojo.getMagicPojo(pojoClass);
		List<PojoFieldSerializer> list = new ArrayList<PojoFieldSerializer>();
		Iterator<MagicAttribute> iterator = magicPojo.getMagicAttributes();
		MagicAttribute magicAttribute;
		while (iterator.hasNext()) {
			magicAttribute = iterator.next();
			list.add(new PojoFieldSerializer(magicAttribute, JSONSerializerFactory
					.getSerializer(magicAttribute.getField().getType())));
		}
		this.serializers = list.toArray(new PojoFieldSerializer[list.size()]);
	}

	@Override
	public void writeJSONString(SerializerWriter writer, Object value) {
		writer.write('{');
		boolean flag = false;
		for (PojoFieldSerializer serializer : serializers) {
			if (flag) {
				serializer.write(writer, value, flag);
				continue;
			}
			flag = serializer.write(writer, value, flag);
		}
		writer.write('}');
	}

}
